package com.flute.haflute.jobbox.child;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.haflute.jobbox.base.RunProcessInterface;
import com.flute.haflute.jobbox.communication.ChildCommunicationService;
import com.flute.haflute.jobbox.communication.ChildListener;
import com.flute.haflute.jobbox.communication.ChildListenerManager;
import com.flute.haflute.jobbox.communication.ClientService2Server;
import com.flute.haflute.jobbox.communication.messages.MessageBase;

/**
 * 启动任务监听接口
 * 
 * 监听主节点发布的任务请求，并将消息传递给后台任务调度线程
 */
public class TaskReceiver extends UnicastRemoteObject implements ChildListener,
		RunProcessInterface {
	private static Logger logger = LoggerFactory.getLogger(TaskReceiver.class);
	private static final long serialVersionUID = 1L;
	private boolean initialized = false;
	private ClientService2Server notifier;

	public TaskReceiver() throws RemoteException {
		super();
		initialized = false;
	}

	@Override
	public void receive(MessageBase message) throws RemoteException {
		CommonService4Child.notifyTracker(message);
	}

	@Override
	public void receive(List<MessageBase> messages) throws RemoteException {
		CommonService4Child.notifyTracker(messages);
	}

	@Override
	public void callMain(String... params) {
		try {
			connect();
			// 添加自己到全局监听池，便于管理，重连等
			ChildListenerManager.add2ListenerCache(this);
			initialized = true;
		} catch (RemoteException e) {
			logger.error(
					"callMain fatal error, will NOT receive any message !!", e);
		}

	}

	@Override
	public boolean isInitialized() {
		return initialized;
	}

	@Override
	public void shutdown() {
		disconnect();
	}

	private void disconnect() {
		if (notifier != null) {
			try {
				notifier.unRegister(ChildContext.getMyID());
			} catch (Throwable e) {
				logger.info("unRegister myself from master error: ", e);
			}
			notifier = null;
		}
	}

	@Override
	public boolean isAlive() throws RemoteException {
		return true;
	}

	@Override
	public void reconnect2Server() throws RemoteException {
		disconnect();
		connect();
	}

	private void connect() throws RemoteException {
		if (notifier == null) {
			// 获得任务消息通知器
			notifier = new ChildCommunicationService().getMasterNotifier();
			// 注册自己为消息接收器
			notifier.register(ChildContext.getMyID(), this);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.flute.haflute.common.RunProcessInterface#restart()
	 */
	@Override
	public void restart() {
		try {
			reconnect2Server();
		} catch (RemoteException e) {
			logger.error("reconnect to master error", e);
		}
	}

}
